<?php
/**
 * (logic)
 */
namespace App\Logic\MonthlyReportLT;

use App\Models\CustomerDelivery\CustomerDelivery;
use App\Models\CustomerDelivery\CustomerDeliveryDetail;
use App\Models\MonthlyReportLT\Payment\PaymentOrder;
use Illuminate\Support\Facades\DB;
class CheckLogisticsOrderCN
{
    public static function exe($date)
    {
        if('null' == $date){
            $time = strtotime('midnight first day of -1 month');
        }else{
            $time = strtotime($date);
        }
        try{
            DB::beginTransaction();
            self::_exePaymentOrderForCNFei($time);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    /**
     * 更新PaymentOrder表国内发货的物流费
     * @param $time
     */
    private static function _exePaymentOrderForCNFei($time){
        $date = date('Y-m-01',$time);
        PaymentOrder::query()
            ->where('report_date',$date)
            ->where('cn_quantity','>',0)
            ->orderBy('id')
            ->chunk(50, function ($items){
                foreach ($items as $item){
                    $deliveryDetails = CustomerDeliveryDetail::query()
                        ->where('delivery_type',CustomerDelivery::DELIVERY_TYPE_CN)
                        ->where('order_no',$item->order_id)
                        ->where('psku_id',$item->psku_id)
                        ->get();
                    $num = 0;
                    $total = 0;
                    foreach ($deliveryDetails as $deliveryDetail){
                        $num += $deliveryDetail->ship_num;
                        $total += ($deliveryDetail->logistics_fee ?: 0) * $deliveryDetail->ship_num;
                    }
                    if($num){
                        $item->cn_fei =  $total / $num;
                        $item->check_status = 0;
                    }else{
                        $item->check_status = 1;
                    }
                    $item->save();
                }
            });
    }
}
